#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
   @Author: 叶建伟
   @Email: yejw46507@hundsun.com
   @Time: 2023/3/30 14:06
   @File: restartServer.py
"""
import json
from time import sleep
import requests

from DataTest.env import Env
from CommonScripts.Logs import logger

headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }


class RequestFailed(Exception):
    pass


class APIRequset:
    def __init__(self, url, data, headers=headers):
        self.url = url
        self.data = data
        self.headers = headers
        self.session = requests.session()
    def doPost(self):
        try:
            # logger.info(f"请求url=====》{self.url}")
            # logger.info(f"请求参数=====》{self.data}")
            # logger.info(f"请求头======》{self.headers}")
            rsp = self.session.post(self.url,self.data,headers=self.headers)
            # logger.info(f"请求结果=====》{rsp.text}")
            if rsp.status_code != 200:
                raise RequestFailed('%s failed', rsp.text)
        except requests.RequestException as e:
            raise RequestFailed('request failed: %s' % str(e))
        else:
            return rsp


    def doGet(self):
        try:
            parameter = '?'
            for key,value in self.data.items():
                parameter =parameter + str(key) + '=' + str(value) + '&'
            url = self.url + parameter[:-1]
            rsp = self.session.get(url, headers=self.headers)
            logger.info(f'url为：{url}')
            logger.info(f"请求头======》{self.headers}")
            print(rsp.text)
            if rsp.status_code != 200:
                raise RequestFailed('%s failed', rsp.text)
        except requests.RequestException as e:
            raise RequestFailed('request failed: %s' % str(e))
        else:
            return rsp
"""
通过url获取登录token
"""
def getToken(url):
    data = None
    while True:
        test = APIRequset(url, data, headers=None)  # 先创建对象
        response = test.doGet()  # 再调用方法
        result = response.cookies.get_dict()
        if result =={}:
            continue
        else:
            headers['Cookie'] = 'JSESSIONID=' + result['JSESSIONID']
            break
    urlLogin = url.replace('/app.htm', '/system/auth.json')
    test1 = APIRequset(urlLogin, data, headers)  # 先创建对象
    loginResponse = test1.doPost()
    jsonResponse = json.loads(loginResponse.text)
    return "Bearer "+jsonResponse["data"]["token"]

"""
查询服务信息，获取服务ID
"""
def getServer(url,token,keyWord):
    headers['Authorization'] = token
    getUrl = url.replace("/app.htm","/dssp/application/authority/query.json")
    data = {'pageNo': '1', 'pageSize': '15', 'name': keyWord}
    test = APIRequset(getUrl, data, headers)
    return test.doPost()

"""
查询服务状态
"""
def getServerStatics(url,token,keyWord):
    headers['Authorization'] = token
    getUrl = url.replace("/app.htm","/dssp/application/getStatics.json")
    data = {'name': keyWord}
    test = APIRequset(getUrl, data, headers)
    return test.doPost()

"""
重启服务
"""
def restartServer(url,token,keyWord):
    headers['Authorization'] = token
    getUrl = url.replace("/app.htm","/dssp/application/console/restartApp.json")
    data = {'forceKill': 'false', 'appId':  keyWord}
    test = APIRequset(getUrl, data, headers)
    return test.doPost()


"""
重启服务并检查状态
"""
def restart(keyWord,env=None):
    env=Env(env)
    url=env.see
    token = getToken(url)
    response = getServer(url, token, keyWord)
    result = json.loads(response.text)
    if result['data']['items']:
        id = result['data']['items'][0]['id']
        restartServer(url, token, id)
        print(f"============{result['data']['items'][0]['name']}开始重启！！=========")

        while True:
            sleep(30)
            response = getServerStatics(url, token, keyWord)
            result1 = response.json()
            if result1['data']['success'] == 1:
                break
        print(f"============{result['data']['items'][0]['name']}重启成功！！=========")
        return True
    else:
        print(f"============服务不存在，重启失败！=========")
        return False




if __name__=='__main__':
    url = "http://f6fea70b0032462db4eb1edcfd9bfa18.vm-a.hep.see.dev.hundsun.com/acm/app.htm"
    keyWord = 'message'
    restart(url, keyWord)